package com.km.wskj.itmonitor.pager.wq.note;

import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.johnpersano.supertoasts.SuperActivityToast;
import com.github.johnpersano.supertoasts.SuperToast;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.wq.note.model.AddCallback;
import com.km.wskj.itmonitor.pager.wq.note.model.AddNoteParms;
import com.km.wskj.itmonitor.pager.wq.note.model.NoteBook;
import com.km.wskj.itmonitor.pager.wq.note.model.NoteDetail;
import com.km.wskj.itmonitor.utils.ListToStringUtils;
import com.zxl.zxlapplibrary.http.callback.StringCallback;
import com.zxl.zxlapplibrary.model.ImageData;
import com.zxl.zxlapplibrary.util.GalleryHelper;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.util.ToolsUtil;
import com.zxl.zxlapplibrary.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StringUtils;
import okhttp3.Call;

public class AddNoteActivity extends LActivity {
    private static final String TAG = "AddNoteActivity";

    @BindView(R.id.sp_notebook)
    Spinner sp_notebook;
    @BindView(R.id.et_title)
    EditText et_title;
    @BindView(R.id.et_content)
    EditText et_content;
    @BindView(R.id.layout_pics)
    ViewGroup layout_pics;
    @BindView(R.id.tv_pics)
    TextView tv_pics;

    MyGridView photoGridView;

    //data
    NoteDetail note;
    List<NoteBook> mNoteBooks;
    NoteBook selectedNB;
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right_text)
    TextView toolBarRightText;
    @BindView(R.id.activity_add_note)
    LinearLayout activityAddNote;

    private List<String> mDatas = new ArrayList<>();//笔记本分类
    private List<String> ids = new ArrayList<>();//笔记本对应id
    private String selectedId;//所选择添加到笔记本的id

    //args
    String nbId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_note);
        ButterKnife.bind(this);

        toolBarTitle.setText("添加笔记");
        toolBarBack.setVisibility(View.VISIBLE);
        toolBarRightText.setText("保存");
        toolBarRightText.setVisibility(View.VISIBLE);
        //args
        if (getIntent().hasExtra("nbId")) {
            nbId = getIntent().getStringExtra("nbId");
        }
        if (getIntent().hasExtra("note")) {
            note = (NoteDetail) getIntent().getSerializableExtra("note");
            toolBarTitle.setText("笔记详情");
            tv_pics.setText("图片附件");
            loadNoteDetail();
        }
        //data
        if (note == null) {
            note = new NoteDetail();
            //如果还有图片参数
            if (getIntent().hasExtra("picpath")) {
                String picpath = getIntent().getStringExtra("picpath");
                note.imgList.add(new ImageData(picpath, 600, 600, ImageData.ScaleType.SCALE_TYPE_FIT_CENTER));
            }
            loadNotebookList();
        }
        //ui
        createPicGrid();
    }


    private void loadNoteDetail() {
        pdc.noteDetail(HTTP_TASK_TAG, note.id, pdc.new NoteDetailCallback(note) {
            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("加载笔记出错：" + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Object o, int i) {
                et_content.setText(note.content);
                et_title.setText(note.title);
                photoGridView.reload();//如果有图就刷新图

                //确定要选择的笔记本是哪个
                nbId = note.info.columnId;
                loadNotebookList();
            }
        });
    }

    private void loadNotebookList() {
        pdc.noteBookList(HTTP_TASK_TAG, new ZxlGenericsCallback<List<NoteBook>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("获取笔记本列表失败!");
                LogUtils.e("error get notebooklist " + call.request().url().toString(), e);
            }

            @Override
            public void onResponse(List<NoteBook> noteBooks, int i) {
                mNoteBooks = noteBooks;
                initSp();
            }
        });
    }

    private void initSp() {
        for (NoteBook nb : mNoteBooks
                ) {
            mDatas.add(nb.typeName);
            ids.add(nb.idX);
        }

        //set sp
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, mDatas);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_notebook.setAdapter(adapter);
        sp_notebook.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                selectedNB = (NoteBook) parent.getItemAtPosition(position);
                selectedId = ids.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectedNB = null;
            }
        });
        if (nbId != null && !nbId.equals("")) {
            int selectedIndex = -1;
            for (int i = 0; i < mNoteBooks.size(); i++) {
                if (mNoteBooks.get(i).idX.equals(nbId)) {
                    selectedIndex = i;
                    break;
                }
            }
            if (selectedIndex >= 0) {
                sp_notebook.setSelection(selectedIndex);
            } else {
                sp_notebook.setSelection(0);
            }
        }
    }

    private void createPicGrid() {
        // 添加照片预览容器
        photoGridView = new MyGridView(this, adapter);
        photoGridView.setListener(photoListener);
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layout_pics.addView(photoGridView.getView(), p);
    }

    private void delImage(final int index) {
        ImageData img = note.imgList.get(index);
        note.imgList.remove(index);
        photoGridView.reload();

       /* pdc.delNotePic(img.imgId, note.id, new WeishuCallback() {
            @Override
            public Object parseNetworkResponse(Response response, int i) throws Exception {
                return null;
            }

            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("删除图片附件出错！");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(Object o, int i) {
                note.imgList.remove(index);
                photoGridView.reload();
            }
        });*/

    }

    MyGridView.MyGridViewAdapter adapter = new MyGridView.MyGridViewAdapter() {
        @Override
        public int rowspacing(MyGridView mg) {
            return 10;
        }

        @Override
        public int colspacing(MyGridView mg) {
            return 10;
        }

        @Override
        public int leftpadding(MyGridView mg) {
            return 10;
        }

        @Override
        public int toppadding(MyGridView mg) {
            return 10;
        }

        @Override
        public int colCount(MyGridView mg) {
            return 4;
        }

        @Override
        public int rowHeight(MyGridView mg) {
            return 0;
        }

        @Override
        public int viewWidth(MyGridView mg) {
            return getScreenWidth() - convertDipToPix(16);
        }

        @Override
        public int count(MyGridView mg) {
            return note.imgList.size() + 1;
        }

        @Override
        public View cell(int index, MyGridView mg) {
            View view = getLayoutInflater().inflate(R.layout.item_takephoto, null);
            ImageView iv = (ImageView) view.findViewById(R.id.iv_dis);
            ImageButton btn_close = (ImageButton) view.findViewById(R.id.btn_close);

            if (index < note.imgList.size()) {
                ImageData imageData = note.imgList.get(index);
                imageData.displayImage(context, iv);
                btn_close.setVisibility(View.VISIBLE);
                btn_close.setTag(Integer.valueOf(index));

                btn_close.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        delImage((Integer) v.getTag());
                    }
                });

            } else {
                btn_close.setVisibility(View.INVISIBLE);
            }

            return view;
        }

        @Override
        public View title(int index, MyGridView mg) {
            return null;
        }

        @Override
        public int titleOffsetY(MyGridView mg) {
            return 0;
        }

        @Override
        public boolean needGridLine(MyGridView mg) {
            return false;
        }
    };

    private MyGridView.MyGridViewListener photoListener = new MyGridView.MyGridViewListener() {


        @Override
        public void onCellTouchDown(int index) {

        }

        @Override
        public void onCellTouchUp(int index) {

        }

        @Override
        public void onCellLongPress(int index) {

        }

        @Override
        public void onCellClick(int index) {
            if (index == note.imgList.size()) {
                //最后一张
                new GalleryHelper().openMuti(context, 6, new GalleryHelper.OnPickMutiPhotoCallback() {
                    @Override
                    public void onPickSucc(List<PhotoInfo> list) {
                        for (PhotoInfo pi : list) {
                            ImageData img = new ImageData(pi.getPhotoPath(), 600, 600, ImageData.ScaleType.SCALE_TYPE_FIT_CENTER);
                            note.imgList.add(img);
                        }
                        photoGridView.reload();
                    }

                    @Override
                    public void onPickFail(String s) {
                        showErrorTip(s);
                    }
                });
            }
        }
    };

    private void upload() {

    }

    //保存笔记的方法
    private ArrayList<String> mImgIds;
    private String title;
    private String content;
    private String imgStr;

    private void save() {

        mImgIds = new ArrayList<>();//用来存放上传图片返回的id

        title = et_title.getText().toString();
        content = et_content.getText().toString();

        if (StringUtils.isEmpty(content)) {
            ToolsUtil.msgbox(context, "笔记正文不能为空！");
            return;
        }
        if (StringUtils.isEmpty(title)) {
            //生成正文标题
            int len = content.length() > 16 ? 16 : content.length();
            title = content.substring(0, len);
        }
        final SuperActivityToast superActivityToast = new SuperActivityToast(context, SuperToast.Type.PROGRESS);
        superActivityToast.setIndeterminate(true);
        superActivityToast.setText("请稍后...");
        superActivityToast.setProgressIndeterminate(true);
        superActivityToast.show();


        for (int i = 0; i < note.imgList.size(); i++) {
            //上传图片一张一张的传
            pdc.uploadPic(HTTP_TASK_TAG, note.imgList.get(i), new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int i) {
                    LogUtils.e(TAG, e);
                }

                @Override
                public void onResponse(String s, int i) {
                    JSONObject json = JSON.parseObject(s);
                    String attach_id = json.getString("attach_id");
                    mImgIds.add(attach_id);

                    //图片都上传完成以后执行操作
                    if (mImgIds.size() == note.imgList.size()) {
                        imgStr = ListToStringUtils.listToString(mImgIds, ",");
                        AddNoteParms add = new AddNoteParms();
                        add.columnId = selectedId;
                        add.title = title;
                        add.content = content;
                        add.imgIds = imgStr;

                        pdc.addNote(HTTP_TASK_TAG, add, new ZxlGenericsCallback<AddCallback>() {
                            @Override
                            public void onError(Call call, Exception e, int i) {
                                LogUtils.e(TAG, e);
                            }

                            @Override
                            public void onResponse(AddCallback addCallback, int i) {
                                superActivityToast.dismiss();
                                normalToasty(addCallback.msg);

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        setResult(RESULT_OK);
                                        finish();
                                    }

                                }, 1000);

                            }
                        });
                    }

                }
            });
        }


    }

    @OnClick({R.id.tool_bar_back, R.id.tool_bar_right_text})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tool_bar_right_text:
                save();
                break;
        }
    }
}
